package com.dk.shiro;

import com.dk.pojo.TPerson;
import com.dk.service.PersonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.xml.ws.Action;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @ClassName PersonRealm
 * @Author RC
 * @date 2020.12.07 11:20
 */
public class PersonLoginRealm extends AuthorizingRealm{
    @Autowired
    private PersonService personService;
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权方法");
        //获取登录用户
        Subject subject = SecurityUtils.getSubject();
        TPerson tPerson = (TPerson) subject.getPrincipal();
        System.out.println("当前登录用户是 :"+tPerson.getPname());
        String perms = "myadd";
        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        List<String> permsList = new ArrayList<>();
        permsList.add(perms);
        auth.addStringPermissions(permsList);
        return auth;
    }
    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证方法");

        //判断账号是否存在
        UsernamePasswordToken token =(UsernamePasswordToken)authenticationToken;
        //通过账号查询
        String username = token.getUsername();
        TPerson tPerson = personService.findUserByUserName(username);
        //校验密码是否正确
        return tPerson == null ? null : new SimpleAuthenticationInfo(tPerson,tPerson.getPwd(),ByteSource.Util.bytes(tPerson.getSalt()), tPerson.getPname());
    }
}
